<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客服</title>
    <style>
        .chat-container {
            width: 600px;
            margin: 20px auto;
            border: 1px solid #5c2d91;
            border-radius: 8px;
            overflow: hidden;
            background-color: #2d1b55;
            color: #ffffff;
        }
        .chat-header {
            background-color: #7b2cbf;
            padding: 15px;
            font-size: 18px;
            font-weight: bold;
        }
        .chat-content {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
        }
        .message {
            margin: 10px 0;
            padding: 10px;
            border-radius: 6px;
            max-width: 70%;
            word-wrap: break-word;
        }
        .user-message {
            background-color: #7b2cbf;
            margin-left: auto;
        }
        .system-message {
            background-color: #4a256d;
            margin-right: auto;
        }
        .message-time {
            font-size: 12px;
            color: #b39ddb;
            text-align: right;
            margin-top: 5px;
        }
        .input-area {
            display: flex;
            padding: 10px;
            border-top: 1px solid #5c2d91;
        }
        .input-area input {
            flex: 1;
            padding: 10px;
            border: 1px solid #5c2d91;
            border-radius: 4px;
            background-color: #3d2269;
            color: #ffffff;
            outline: none;
        }
        .input-area button {
            margin-left: 10px;
            padding: 0 20px;
            background-color: #7b2cbf;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .input-area button:hover {
            background-color: #9c27b0;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-header">智能客服</div>
    <div class="chat-content" id="chatContent">
        <div class="message system-message">
            您好！我是智能客服助手<br>
            输入"统计"可查看实时课程统计信息
        </div>
    </div>
    <div class="input-area">
        <input type="text" id="messageInput" placeholder="请输入指令...">
        <button onclick="sendMessage()">发送</button>
    </div>
</div>

<script>
    function sendMessage() {
        const input = document.getElementById("messageInput");
        const msg = input.value.trim();
        if (!msg) return;

        const chatContent = document.getElementById("chatContent");
        const time = new Date().toLocaleTimeString();

        // 添加用户消息
        chatContent.innerHTML += `
                <div class="message user-message">
                    ${msg}
                    <div class="message-time">${time}</div>
                </div>
            `;
        input.value = "";
        scrollToBottom(chatContent);

        // 调用后端接口获取实时数据
        fetch(`/support/message?message=${encodeURIComponent(msg)}`)
            .then(res => {
                if (!res.ok) throw new Error(`后端接口异常（状态码：${res.status}）`);
                return res.json();
            })
            .then(data => {
                console.log("后端返回数据:", data); // 调试用

                // 根据后端数据结构处理响应
                if (data.action && data.action.type === "statistics") {
                    // 处理统计信息
                    const statsData = data.action.data;
                    if (statsData) {
                        const totalCourses = statsData.totalCourses || 0;
                        const coursesByTeacher = statsData.coursesByTeacher || {};

                        let statsText = "课程统计信息如下<br>";
                        statsText += `总课程数：${totalCourses} 门<br>`;
                        statsText += "各教师课程数量：<br>";

                        const teacherEntries = Object.entries(coursesByTeacher);
                        if (teacherEntries.length === 0) {
                            statsText += "• 暂无教师数据";
                        } else {
                            teacherEntries.forEach(([name, count], index) => {
                                const lineBreak = index === teacherEntries.length - 1 ? "" : "<br>";
                                statsText += `• ${name}：${count} 门${lineBreak}`;
                            });
                        }

                        chatContent.innerHTML += `
                            <div class="message system-message">
                                ${statsText}
                                <div class="message-time">${time}</div>
                            </div>
                        `;
                    } else {
                        chatContent.innerHTML += `
                            <div class="message system-message">
                                统计信息数据为空
                                <div class="message-time">${time}</div>
                            </div>
                        `;
                    }
                } else {
                    // 其他消息处理
                    const reply = data.answer || data.action?.message || "请输入'统计'查看课程信息";
                    chatContent.innerHTML += `
                        <div class="message system-message">
                            ${reply}
                            <div class="message-time">${time}</div>
                        </div>
                    `;
                }
                scrollToBottom(chatContent);
            })
            .catch(error => {
                console.error("请求错误:", error);
                chatContent.innerHTML += `
                    <div class="message system-message">
                        请求失败：${error.message}
                        <div class="message-time">${time}</div>
                    </div>
                `;
                scrollToBottom(chatContent);
            });
    }

    function scrollToBottom(el) {
        el.scrollTop = el.scrollHeight;
    }

    // 回车发送
    document.getElementById("messageInput").addEventListener("keydown", e => {
        if (e.key === "Enter") sendMessage();
    });
</script>
</body>
</html>